import { Banner } from "@/entities/banner.entity";
import getInheritedFieldDescriptions from "@/utils/getInheritedFieldDescriptions";
import { Context } from "koa";
import path from "path";
import { ColumnMetadataArgs } from "typeorm/metadata-args/ColumnMetadataArgs";
import fs from 'fs';
import { TableInfo } from "@/entities/tableInfo.entity";
import { FieldInfo } from "@/entities/fieldInfo.entity";
import { IndexInfo } from "@/entities/indexInfo.entity";
/**首字母转小写 */
function firstLetterToLowerCase(str: string) {
    return str.charAt(0).toLowerCase() + str.slice(1);
}

/**
 * 创建文件
 * @param content 
 * @param dir 开头不带 / 当前目录已在src下面
 */
const create = async (content: string, dir: string) => {

    // const filePath = path.join(__dirname, '../'+dir);
    // await fs.writeFileSync(filePath, content);


}


/**
 * 创建dto文件
 * @param name 
 * @param remain 
 */
const createDtoFile = (name: string, remain: ColumnMetadataArgs[]) => {

    const dtoImport = `
    import { IsNotEmpty, IsString,  IsOptional, IsInt,  MaxLength,ArrayMinSize,IsArray ,ValidateNested} from 'class-validator';
    import { BaseRequestListDto } from './baseRequestList.dto';
    import { Type  } from 'class-transformer';
    
    `


    // 生成createDco
    let createDto = `
    export class Create${name}Dto {
    `
    let updateDto = `
    export class Update${name}Dto {
        @IsNotEmpty({ message: 'id不能为空' })
        id!:number;

    `
    let queryDto = `
    export class Query${name}Dto extends BaseRequestListDto {
    `

    let deleteDto = `
    export class Delete${name}Dto {
      @IsNotEmpty({ message: 'ID列表不能为空' })
      @IsInt({ each: true, message: '每个ID必须是整数' })
      ids!: number[];
    }
    
    `
    let selectOneDto = `
    export class SelectOne${name}Dto {
      @IsNotEmpty({ message: 'ID不能为空' })
      id!: number;
    }
    
    
    `
    let sortItem = `
    class Sort${name}ItemDto {
        @IsInt({ message: 'id必须是整数' })
        @IsNotEmpty({ message: 'ID不能为空' })
        id!: number;

        @IsInt({ message: 'sort必须是整数' })
        @IsNotEmpty({ message: '排序不能为空' })
        sortOrder!: number;
    }`



    let sortDto = `
    export class Sort${name}Dto {
        @IsArray({ message: 'list必须是数组' })
        @ArrayMinSize(1, { message: 'list不能为空数组' })
        @ValidateNested({ each: true }) // 校验每个数组项
        @Type(() => Sort${name}ItemDto) // 必须配合class-transformer
        list!: Sort${name}ItemDto[];
    }    
    
    `

    let responseDto = `
    export class ${name}ResponseDto extends BaseRequestListDto {
        /**id*/
        @IsOptional()
        id?:number;

        /**创建时间*/
        @IsOptional()
        createdAt?:string;

        /**更新时间*/
        @IsOptional()
        updatedAt?:string;


    `

    remain.forEach(item => {
        /**当字段可为空，或有默认值的，可以为空 */
        const isCanEmpty = item.options.nullable || item.options.hasOwnProperty("default");
        const isNumber = ["tinyint", 'int', 'integer', 'smallint', 'mediumint', 'bigint', 'decimal', 'numeric'].indexOf(item.options.type as string) != -1;

        createDto += `
            /**${item.options.comment}*/
            ${isCanEmpty ? `@IsOptional()` : `@IsNotEmpty({ message: '${item.options.comment}不能为空' })`}
            ${item.propertyName}${isCanEmpty ? "?" : "!"}:${isNumber ? "number" : "string"}; 

        `
        updateDto += `
            /**${item.options.comment}*/
            @IsOptional()
            ${item.propertyName}?:${isNumber ? "number" : "string"}; 

        `
        queryDto += `
            /**${item.options.comment}*/
            @IsOptional()
            ${item.propertyName}?:${isNumber ? "number" : "string"}; 

        `
        responseDto += `
            /**${item.options.comment}*/
            @IsOptional()
            ${item.propertyName}?:${isNumber ? "number" : "string"}; 

        `


    })
    createDto += `}
    `;
    updateDto += `}
    `;
    queryDto += `}
    `;
    responseDto += `}
    `;


    const dtoStr = dtoImport + createDto + updateDto + queryDto + deleteDto + selectOneDto + sortItem + sortDto + responseDto
    create(dtoStr, `dto/${firstLetterToLowerCase(name)}.dto.ts`)
    return dtoStr
}

/**
 * 创建路由文件
 * @param name 
 * @param data 
 */
const createRouterFile = (name: string, data: ColumnMetadataArgs[]) => {
    const str = `
    import Router from '@koa/router';    
    import ${name}Controller from '@/controllers/${firstLetterToLowerCase(name)}.controller'
    const ${firstLetterToLowerCase(name)}Router = new Router({ prefix: '/${firstLetterToLowerCase(name)}' });
    ${firstLetterToLowerCase(name)}Router.post('/selectList', ${name}Controller.selectList);
    ${firstLetterToLowerCase(name)}Router.post('/selectOne', ${name}Controller.selectOne);
    ${firstLetterToLowerCase(name)}Router.post('/add', ${name}Controller.add);
    ${firstLetterToLowerCase(name)}Router.post('/update', ${name}Controller.update);
    ${firstLetterToLowerCase(name)}Router.post('/delete', ${name}Controller.delete);    
    ${firstLetterToLowerCase(name)}Router.post('/sort', ${name}Controller.sort);    

    export default ${firstLetterToLowerCase(name)}Router;
    
    `
    create(str, `routes/${firstLetterToLowerCase(name)}.router.ts`)
    return str

}

/**
 * 创建控制器文件
 * @param name 
 * @param data 
 */
const createControllersFile = (name: string, data: ColumnMetadataArgs[]) => {
    const str = `
import { Context } from 'koa';
import { validateDto } from '@/utils/validateDto';
import { Create${name}Dto, Update${name}Dto, Query${name}Dto, Delete${name}Dto, SelectOne${name}Dto,Sort${name}Dto } from '@/dto/${firstLetterToLowerCase(name)}.dto';
import ${firstLetterToLowerCase(name)}Service from '@/services/${firstLetterToLowerCase(name)}.service';

class ${name}Controller {
    async selectList(ctx: Context) {

        const reqData = ctx.request.body as Query${name}Dto;
        const errors = await validateDto(Query${name}Dto, reqData);
        if (errors) {
            ctx.body = errors;
            return
        }
        let resData = await ${firstLetterToLowerCase(name)}Service.selectList(reqData)
        ctx.body = {
            code: 200,
            message: "列表查询成功",
            data:resData
        };
    }
    async selectOne(ctx: Context) {
        const reqData = ctx.request.body as SelectOne${name}Dto;
        let resData = await ${firstLetterToLowerCase(name)}Service.selectOne(reqData)

        
        ctx.body = {
            code: 200,
            message:"详情查询成功",
            data: resData,

        };
    }

    async add(ctx: Context) {
        const userId = ctx.state.userId as number;
        const reqData = ctx.request.body as Create${name}Dto;
        //reqData.userId = reqData.userId || userId; //暂时注释
        const errors = await validateDto(Create${name}Dto, reqData);
        if (errors) {
            ctx.body = errors;
            return
        }
        const resData = await ${firstLetterToLowerCase(name)}Service.add(reqData);   
        
        ctx.body = {
        code: 200,
        message:"添加成功",
        data:{id:resData.id},
        };

    }

    async update(ctx: Context) {
        const reqData = <Update${name}Dto>ctx.request.body
        const errors = await validateDto(Update${name}Dto, reqData);
        if (errors) {
            ctx.body = errors;
            return
        }
        const resData = await ${firstLetterToLowerCase(name)}Service.update(reqData);   


        ctx.body = {
            code: 200,
            message:"更新成功",
            data: {},
        };

    }
    async delete(ctx: Context) {
        const reqData = ctx.request.body as Delete${name}Dto;
        const errors = await validateDto(Delete${name}Dto, reqData);
        if (errors) {
            ctx.body = errors;
            return
        }
        const resData = await ${firstLetterToLowerCase(name)}Service.delete(reqData);

        ctx.body = {
            code: 200,
            message:"删除成功",
            data: {},
        };

    }
    async sort(ctx: Context) {
        const reqData = ctx.request.body as Sort${name}Dto;
        const errors = await validateDto(Sort${name}Dto, reqData);
        if (errors) {
            ctx.body = errors;
            return
        }
        const resData = await ${firstLetterToLowerCase(name)}Service.sort(reqData);
    
        ctx.body = {
            code: 200,
            message:"排序成功",
            data: {},
        };
    
    }

}

export default new ${name}Controller();   
    
    `
    create(str, `controllers/${firstLetterToLowerCase(name)}.controller.ts`)

    return str

}

/**
 * 创建服务文件
 * @param name 
 * @param data 
 */
const createServicesFile = (name: string, data: ColumnMetadataArgs[]) => {
    const str = `
import { Create${name}Dto, Update${name}Dto, Query${name}Dto, Delete${name}Dto, SelectOne${name}Dto ,Sort${name}Dto} from '@/dto/${firstLetterToLowerCase(name)}.dto';
import ${firstLetterToLowerCase(name)}Repository from '@/repositories/${firstLetterToLowerCase(name)}.repository';


class ${name}Service {

    /**
     * 创建
     * @param data  
     * @returns 
     */

    async add(data: Create${name}Dto) {
        // 检查是否已存在
        const findOne = await ${firstLetterToLowerCase(name)}Repository.${firstLetterToLowerCase(name)}Exists(data.name);
        if (findOne) {
            if (findOne.name == data.name) {
                throw new Error('标题已存在！');
            }

        }
        // 创建
        return ${firstLetterToLowerCase(name)}Repository.create(data);
    }
    async update(data: Update${name}Dto) {
          // 1. 检查是否存在
        const existingCategory = await ${firstLetterToLowerCase(name)}Repository.findById(data.id );
        if (!existingCategory) {
            throw new Error("数据不存在")
        }

        
        const findOne = await ${firstLetterToLowerCase(name)}Repository.findExcludeId(data);
        if (findOne) {
            if (findOne.name == data.name) {
                throw new Error('名称已存在！');
            }
 
        }
        // 更新
        return ${firstLetterToLowerCase(name)}Repository.update(data);
    }

    async selectOne(reqData: SelectOne${name}Dto) {
        return ${firstLetterToLowerCase(name)}Repository.findById(reqData.id)


    }

    async selectList(reqData: Query${name}Dto) {
        return ${firstLetterToLowerCase(name)}Repository.selectList(reqData)


    }
    async delete(reqData: Delete${name}Dto) {
        let res = await ${firstLetterToLowerCase(name)}Repository.delete(reqData);
        if (!res) {
            throw new Error("id不存在，无删除记录！")
        }
        return res


    }
    async sort(reqData: Sort${name}Dto) {
      let res = await ${firstLetterToLowerCase(name)}Repository.sort(reqData);
      return res


    }

}

export default new ${name}Service();    
    
    `
    create(str, `services/${firstLetterToLowerCase(name)}.service.ts`)

    return str

}

/**
 * 创建仓库文件
 * @param name 
 * @param data 
 */
const createRepositoriesFile = (name: string, data: ColumnMetadataArgs[]) => {
    let assignmentStr = "";
    let selectStr = `
            '${firstLetterToLowerCase(name)}.id',
            '${firstLetterToLowerCase(name)}.createdAt',
            '${firstLetterToLowerCase(name)}.updatedAt',`
    data.forEach(item => {
        assignmentStr += `
            ${firstLetterToLowerCase(name)}.${item.propertyName} = data.${item.propertyName};`
        selectStr += `
            '${firstLetterToLowerCase(name)}.${item.propertyName}',`

    })



    const str = `

import { AppDataSource } from '@/config/AppDataSource';
import { Create${name}Dto, Update${name}Dto, Query${name}Dto, Delete${name}Dto,Sort${name}Dto } from '@/dto/${firstLetterToLowerCase(name)}.dto';
import { ${name} } from '@/entities/${firstLetterToLowerCase(name)}.entity';
import { In } from 'typeorm';
export class ${name}Repository {
    private repositor = AppDataSource.getRepository(${name});
    constructor() { }

    async findExcludeId(data: Update${name}Dto) {
        const conflictCategory = await this.repositor
            .createQueryBuilder('${firstLetterToLowerCase(name)}')
            .where('${firstLetterToLowerCase(name)}.id != :id', { id: data.id })
            .andWhere('(${firstLetterToLowerCase(name)}.name = :name)', { name: data.name })
            .getOne();
        return conflictCategory
    }


    async ${firstLetterToLowerCase(name)}Exists(name: string) {
        const c = await this.repositor.findOne({
            where: [
                { name },
            ],
        });
        return c;
    }

    async findById(id: number) {

        const item = await this.repositor.findOneBy({
            id
        })
        return item;
    }

    async create(data: Create${name}Dto): Promise<${name}> {
        const ${firstLetterToLowerCase(name)} = new ${name}();
        ${assignmentStr}
        
        const result = await this.repositor.save(${firstLetterToLowerCase(name)})
        // console.log("result", result)
        return result;
    }
    async update(data: Update${name}Dto) {
        const ${firstLetterToLowerCase(name)} = new ${name}();
        ${firstLetterToLowerCase(name)}.id = data.id;
        ${assignmentStr}

        return this.repositor.save(${firstLetterToLowerCase(name)});

    }



    async selectList(reqData: Query${name}Dto) {
        const { page, pageSize, name, orderBy,  comment,status,fromDate, toDate } = reqData;

        const queryBuilder = this.repositor
            .createQueryBuilder('${firstLetterToLowerCase(name)}')
            .select([
                ${selectStr}
            ]);

        if (name) {
            queryBuilder.andWhere('${firstLetterToLowerCase(name)}.name LIKE :name', { name: \`%\${name}%\` });
        }
        if (comment) {
            queryBuilder.andWhere('${firstLetterToLowerCase(name)}.comment LIKE :comment', { comment: \`%\${comment}%\` });
        }
        if (status) {
            queryBuilder.andWhere('${firstLetterToLowerCase(name)}.status = :status', { status });
        }
                // 添加创建日期范围查询
        if (fromDate && toDate) {
            queryBuilder.andWhere('${firstLetterToLowerCase(name)}.createdAt BETWEEN :fromDate AND :toDate', {
                fromDate: new Date(fromDate),
                toDate: new Date(\`\${toDate}T23:59:59.999Z\`)

            });
        } else if (fromDate) {
            queryBuilder.andWhere('${firstLetterToLowerCase(name)}.createdAt >= :fromDate', {
                fromDate: new Date(fromDate)
            });
        } else if (toDate) {
            queryBuilder.andWhere('${firstLetterToLowerCase(name)}.createdAt <= :toDate', {
                toDate: new Date(\`\${toDate}T23:59:59.999Z\`)

            });
        }
        const [sortBy, sortOrder] = orderBy.split(" ")
        const [${firstLetterToLowerCase(name)}, total] = await queryBuilder
            .orderBy(\`${firstLetterToLowerCase(name)}.\${sortBy}\`, sortOrder.toLocaleUpperCase() as "ASC" | "DESC")
            .skip((page - 1) * pageSize)
            .take(pageSize)
            .getManyAndCount();
        return {
            list: ${firstLetterToLowerCase(name)},
            total,
            page,
            pageSize,
            totalPages: Math.ceil(total / pageSize),
        };


    }
    async delete(reqData: Delete${name}Dto) {
        const result = await this.repositor.delete({
            id: In(reqData.ids)
        });
        return !!result.affected;

    }
    async sort(reqData: Sort${name}Dto) {

        const queryRunner = AppDataSource.createQueryRunner();

        await queryRunner.connect();
        await queryRunner.startTransaction();

        try {
            for (const item of reqData.list) {
                await queryRunner.manager.update(
                ${name},
                item.id,
                { sortOrder: item.sortOrder }
                );
            }

            await queryRunner.commitTransaction();
            return { success: true };
        } catch (err) {
            await queryRunner.rollbackTransaction();
        throw err;
        } finally {
            await queryRunner.release();
        }
    }
}

export default new ${name}Repository();
    
    `
    create(str, `repositories/${firstLetterToLowerCase(name)}.repository.ts`)

    return str
}
/**
 * 创建前端弹窗组件文件
 * @param name 
 * @param data 
 */
const editModalFile = (name: string, data: ColumnMetadataArgs[]) => {
    let initialValuesStr = '';
    let formItemStr = ''
    data.forEach(item=>{
        if(item.options.hasOwnProperty("default")){
            initialValuesStr +=`
                ${item.propertyName}:${item.options.default},`
        }else{
            initialValuesStr +=`
                ${item.propertyName}:"",`
        }

        if(item.propertyName=="status"){
            formItemStr+= `
                <ProFormSwitch
                    checkedChildren="开启"
                    unCheckedChildren="关闭"
                    label="状态"
                    name="status"
                    initialValue={true}
                />            
            `


        }else if(item.propertyName=="comment"){
            formItemStr+=`
                <ProFormTextArea
                    name='comment'
                    label="描述"
                    placeholder="请输入描述"
                />
            `
        }else{

            formItemStr+= `
                <ProFormText
                    name='${item.propertyName}'
                    label="${item.options.comment}"
                    
                />
            
            `


        }




    })


    const str = `
import { Col, message, Modal, Row, Space } from 'antd';
import React, { PropsWithChildren, useEffect, useRef, useState } from 'react';
import { dataProps } from '..';
import { ProForm, ProFormInstance, ProFormSwitch, ProFormText, ProFormTextArea } from '@ant-design/pro-components';
import { addApi, selectOneApi, updateApi } from '../services';
interface CreateFormProps {
    id?: number;
    modalVisible: boolean;
    onCancel: () => void;
}

const EditModal: React.FC<PropsWithChildren<CreateFormProps>> = (props) => {
    const initialValues: dataProps = {
        ${initialValuesStr}
    };


    const { modalVisible, onCancel, id } = props;
    const formRef = useRef<ProFormInstance<dataProps>>();
    const [currentItem, setCurrentItem] = useState<dataProps>(initialValues)
    useEffect(() => {
        if (modalVisible) {
            if (id) {
                selectOne()
            } else {
                formRef.current?.resetFields();
                setCurrentItem(initialValues)
            }
        }
    }, [modalVisible])


    const selectOne = async () => {
        const hide = message.loading("正在获取详情")
        const res = await selectOneApi(id);
        if (res.code == 200) {
            res.data.status = !!res.data.status
            setCurrentItem(res.data);
            formRef.current?.setFieldsValue(res.data);

        }
        hide()
    }

    const formItemLayout = {
        labelCol: { span: 6 },
        wrapperCol: { span: 16 },
    }
    return (
        <Modal
            title="编辑"
            width={600}
            open={modalVisible}
            onCancel={() => onCancel()}
            footer={null}
        >
            <ProForm<dataProps>

                formRef={formRef}
                {...formItemLayout}
                layout='horizontal'
                submitter={{
                    render: (props, doms) =>
                        <Row>
                            <Col span={14} offset={4}>
                                <Space>{doms}</Space>
                            </Col>
                        </Row>

                }}
                onFinish={async (values) => {
                    values.status = Number(values.status)
                    const hide = message.loading("正在提交！")
                    const submitFun = id ? updateApi : addApi;
                    const subData = {
                        ...values
                    }
                    if (id) {
                        subData.id = id
                    }

                    const res = await submitFun(subData)
                    hide()
                    if (res.code != 200) {

                    } else {
                        message.success("提交成功")
                        onCancel()
                    }
                }}
            >
                <ProFormText
                    name="id"
                    label="id"
                    disabled
                />
               ${formItemStr}

            </ProForm>



        </Modal>
    );
};

export default EditModal;

    
    
    `
    return str


}
/**
 * 创建列表文件
 * @param name 
 * @param data 
 */
const webListFile = (name: string, data: ColumnMetadataArgs[]) => {
    let dataPropsStr = '';
    data.forEach(item=>{
        const isNumber = ["tinyint", 'int', 'integer', 'smallint', 'mediumint', 'bigint', 'decimal', 'numeric'].indexOf(item.options.type as string) != -1;
        dataPropsStr+=`
            ${item.propertyName}${item.options.nullable?"?":""}:${isNumber?"number":"string"};`

    })



    const str = `
    import {
	ActionType,
	DragSortTable,
	PageContainer,
	ProColumns,
} from '@ant-design/pro-components';
import { Button, Divider, message, Popconfirm } from 'antd';
import React, { useRef, useState } from 'react';
import EditModal from './components/EditModal';
import { deleteApi, selectListApi, sortApi } from './services';
import { DeleteOutlined, FormOutlined } from '@ant-design/icons';
export type dataProps = {
	id?: number;
    ${dataPropsStr}
};
const Page: React.FC<unknown> = () => {
	const [handleModalInfo, setHandleModalInfo] = useState<{ visible: boolean, id?: number }>({
		visible: false
	});
	

	const actionRef = useRef<ActionType>();
	const [dataSource, setDataSource] = useState<any[]>([])
	const deleteItem = async (id: number) => {
		const res = await deleteApi(id)
		if (res.code == 200) {
			message.success("删除成功")
			actionRef.current?.reload()
		}
	}

	const columns: ProColumns<any>[] = [
		{

			title: '日期',
			dataIndex: 'date',
			hideInTable:true,
			valueType:"dateRange"
		},
		{
			title: '排序',
			dataIndex: 'sortOrder',
			width: "70px",
			hideInForm: true,
			hideInSearch: true,
			render: (dom, rowData, index) => {
				return (
					<span className="customRender">{rowData.sortOrder}</span>
				);
			},

		},
        {
			title: 'id',
			dataIndex: 'id',
			width: "60",
		},
		{
			title: '名称',
			dataIndex: 'name',
			width: "120px",
		},
		
		{
			title: '描述',
			dataIndex: 'comment',
			width: "100px",
			valueType: 'text',
		},

		{
			title: '状态',
			dataIndex: 'status',
			width: "70px",
			hideInSearch: true,
			valueEnum: {
				0: { text: '禁用', status: 'Error' },
				1: { text: '启用', status: 'Success' },

			},

		},
		{
			title: '创建时间',
			dataIndex: 'createdAt',
			width: "150px",
			hideInForm: true,
			hideInSearch: true,

		},
		{
			title: '更新时间',
			dataIndex: 'updatedAt',
			width: "150px",
			hideInForm: true,
			hideInSearch: true

		},

		{
			title: '操作',
			dataIndex: 'option',
			width: "70px",
			valueType: 'option',
			render: (_, record) => (
				<>
					<FormOutlined className='e_icon' onClick={() => {
						setHandleModalInfo({
							visible: true,
							id: record.id
						})
					}} />

					<Divider type="vertical" />
					<Popconfirm
						title="删除"
						description="确定删除当前分类？"
						onConfirm={() => { deleteItem(record.id) }}
					>
						<DeleteOutlined className='d_icon' />
					</Popconfirm>
				</>
			),
		},
	];

	const handleDragSortEnd3 = (
		beforeIndex: number,
		afterIndex: number,
		newDataSource: any,
	) => {
		setDataSource(newDataSource)
	};


	const sortClick = async () => {
		const res = await sortApi(dataSource.map((item, i) => { return { id: item.id, sortOrder: i + 1 } }))
		if (res.code == 200) {
			message.success('修改列表排序成功');
			actionRef.current?.reload()
		}
	}

	const scrollX = columns.reduce((pre, next) => {
		return pre + parseInt(next.width + "")
	}, 0)

	return (
		<PageContainer
			header={{
				title: 'banner设置',
			}}
		>
			<DragSortTable<any>
				headerTitle="查询表格"
				actionRef={actionRef}
				rowKey="id"
				search={{
					labelWidth: 120,
				}}
				toolBarRender={() => [
					<Button
						key="soort"
						type="primary"
						onClick={sortClick}
					>
						排序
					</Button>,
					<Button
						key="1"
						type="primary"
						onClick={() => setHandleModalInfo({ visible: true })}
					>
						新建
					</Button>,
				]}
				dataSource={dataSource}
				request={async (params, sorter, filter) => {
					
					let orderBy = 'sortOrder asc';
					const objArr = Object.keys(sorter);
					// 有排序字段,暂时支持单字段
					if (objArr.length > 0) {
						const file = objArr[0];
						if (sorter[file] == "descend") {
							orderBy = \`\${file} desc\`
						} else {
							orderBy = \`\${file} asc\`
						}
					}

					const { current, pageSize, date,...other } = params
					const { data, code } = await selectListApi({
						page: current,
						pageSize: pageSize,
						orderBy,
						fromDate:date?.[0]||undefined,
						toDate:date?.[1]||undefined,
						...other

					});
					setDataSource(data.list)
					return {
						success: code == 200,
						total: data.total || 0
					};
				}}
				columns={columns}
				pagination={{
					pageSize: 10,
					onChange: (page) => console.log(page),
				}}
				onDragSortEnd={handleDragSortEnd3}
				dragSortKey="sortOrder"

				scroll={{
					x: scrollX,
				}}
			/>
			<EditModal
				id={handleModalInfo.id}
				onCancel={() => { setHandleModalInfo({ visible: false }); actionRef.current?.reload() }}
				modalVisible={handleModalInfo.visible}
			>
			</EditModal>
		</PageContainer>
	);
};

export default Page;

    
    
    `
    return str
}

/**
 * 创建前端接口文件
 * @param name 
 * @param data 
 */
const webApiFile = (name: string, data: ColumnMetadataArgs[]) => {
    const str = `
import { request } from "@umijs/max";
export const addApi = (data: any) => {
  return request('/${firstLetterToLowerCase(name)}/add', {
    method: 'POST',
    data: data,
  });
}

export const selectListApi = (data: any) => {
  return request('/${firstLetterToLowerCase(name)}/selectList', {
    method: 'POST',
    data: data,
  });
}

export const deleteApi = (id: number) => {
  return request('/${firstLetterToLowerCase(name)}/delete', {
    method: 'POST',
    data: {
      ids:[id]
    },
  });
}
export const updateApi = (data: any) => {
  return request('/${firstLetterToLowerCase(name)}/update', {
    method: 'POST',
    data: data,
  });
}

export const sortApi = (data: any[]) => {
  return request('/${firstLetterToLowerCase(name)}/sort', {
    method: 'POST',
    data: {list:data},
  });
}

export const selectOneApi = (id: any) => {
  return request('/${firstLetterToLowerCase(name)}/selectOne', {
    method: 'POST',
    data: { id },
  });
}
    
    
    `
    return str
}





const createFile = (ctx: Context) => {
    const name = 'IndexInfo'
    const data = getInheritedFieldDescriptions(IndexInfo);
    // 排除一些字段，新增不用处理的
    const excludes = [
        {
            "propertyName": "id",
            "mode": "regular",
            "options": {
                "name": "id",
                "type": "int",
                "comment": "主键ID",
                "primary": true
            }
        },

        {
            "propertyName": "createdAt",
            "mode": "createDate",
            "options": {
                "name": "created_at",
                "type": "datetime",
                "nullable": false,
                "comment": "创建时间",
                "precision": 0
            }
        },
        {
            "propertyName": "updatedAt",
            "mode": "updateDate",
            "options": {
                "name": "updated_at",
                "type": "datetime",
                "onUpdate": "CURRENT_TIMESTAMP",
                "nullable": false,
                "comment": "更新时间",
                "precision": 0
            }
        },
    ];
    //排除日期后剩下的
    const remain = data.filter((re) => excludes.findIndex(ex => re.propertyName == ex.propertyName) == -1)

    //创建dto
    const dtoStr = createDtoFile(name, remain)
    //创建路由
    const router = createRouterFile(name, remain);

    //创建控制器

    const controllersStr = createControllersFile(name, remain);

    const services = createServicesFile(name, remain)

    const reStr = createRepositoriesFile(name, remain)

    const editModalStr = editModalFile(name, remain)

    const webListStr = webListFile(name, remain)

    const webApiStr = webApiFile(name, remain)

    ctx.body = {
        code: 200,
        message: "创建成功",
        data: {
            dto: dtoStr,
            router: router,
            controllers: controllersStr,
            services: services,
            repositories: reStr,
            editModal: editModalStr,
            webApi: webApiStr,
            webList: webListStr,


        }
    }

}
export default createFile


